<template>
  <div style="margin-top:0">
    <!--询盘报价成交-->
    <div class="data-title">
        <div class="title-left">
           <div class="title-item choose">询盘报价成交</div>
        </div>
        <div class="title-right">
            <el-date-picker
              @change="getTopData"
              style="width:210px;margin-right: 10px"
              size="mini"
              value-format="yyyy-MM-dd"
              v-model="listQuery1.date"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          <el-select @change="getTopData" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery1.goodsClass" >
            <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
          </el-select>
          <el-input size="mini" @change="getTopData" v-if="listQuery1.goodsClass" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery1.brandName"></el-input>
          <el-select @change="getTopData" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery1.kingGoodsId" filterable>
            <el-option
              v-for="item in goodsList"
              :key="item.kingId"
              :label="item.goodsSn"
              :value="item.kingId">
            </el-option>
          </el-select>
          <el-select size="mini" v-model="listQuery1.userIds"
                     collapse-tags
                     clearable @change="getTopData"  placeholder="请选择人员" multiple>
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
        </div>
     </div>
    <div class="order-block">
      <div class="inquiry-block">
        <el-row :gutter="8">
          <el-col :span="8">
            <div class="data-block" style="height:360px">
               <div id="funnelChart" class="charts-div" style="height:360px;background: #fff"></div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="data-block" style="height:360px;position: relative">
              <div style="display: flex;justify-content: center;align-items: center;height:100%;position: relative">
                <div style="position: absolute;font-size: 16px;color:#999;text-align: center;width:100%;margin-top:55px">询盘成交率</div>
                <el-progress type="circle" :percentage="orderRate" :width="260" color="#69d1ad" :stroke-width="30"></el-progress>
              </div>
              <div style="text-align: center;font-size: 16px;position: absolute;bottom: 16px;width: 100%;color: #5b5b5b;">询盘成交率=成交数量/询盘数量*100%</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="data-block" style="height:360px;">
              <div id="pieChart" class="charts-div" style="height:360px;background: #fff"></div>
            </div>
          </el-col>
        </el-row>
      </div>

    </div>

    <!--人员询盘成交-->
    <div class="data-title" style="margin-top:10px" v-if="pUserInquiryAnalysis">
      <div class="title-left">
        <div class="title-item choose">人员询盘成交</div>
      </div>
      <div class="title-right">
        <el-date-picker
          @change="getBarData"
          style="width:210px;margin-right: 10px"
          size="mini"
          value-format="yyyy-MM-dd"
          v-model="listQuery2.date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
        <el-select @change="getBarData" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery2.goodsClass" >
          <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
        </el-select>
        <el-input size="mini" @change="getBarData" v-if="listQuery2.goodsClass" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery2.brandName"></el-input>
        <el-select @change="getBarData" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery2.kingGoodsId" filterable>
          <el-option
            v-for="item in goodsList"
            :key="item.kingId"
            :label="item.goodsSn"
            :value="item.kingId">
          </el-option>
        </el-select>
        <el-select size="mini" v-model="listQuery2.userIds"
                   collapse-tags
                   clearable @change="getBarData"  placeholder="请选择人员" multiple>
          <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="data-block" style="margin-top: 10px" v-if="pUserInquiryAnalysis">
      <div id="barChart" style="height: 350px" class="charts-div" v-loading="listLoading2"></div>
    </div>

    <!--报价时长-->
    <div class="data-title" style="margin-top: 10px">
      <div class="title-left">
        <div class="title-item choose" >询盘报价时长分析</div>
      </div>
      <div class="title-right">
        <el-date-picker
          @change="getPieData2"
          style="width:210px;margin-right: 10px"
          size="mini"
          value-format="yyyy-MM-dd"
          v-model="listQuery3.date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
        <el-select @change="getPieData2" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery3.goodsClass" >
          <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
        </el-select>
        <el-input size="mini" @change="getPieData2" v-if="listQuery3.goodsClass" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery3.brandName"></el-input>
        <el-select @change="getPieData2" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery3.kingGoodsId" filterable>
          <el-option
            v-for="item in goodsList"
            :key="item.kingId"
            :label="item.goodsSn"
            :value="item.kingId">
          </el-option>
        </el-select>
        <el-select size="mini" v-model="listQuery3.userIds"
                   collapse-tags
                   clearable @change="getPieData2"  placeholder="请选择人员" multiple>
          <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="order-block">
      <div class="data-block pie-block">
        <div class="pie-menu">
          <div class="pie-menu-item" :class="{'choose':cutIndex3 == 1}" @click="changeItem3(1)">报价数量</div>
          <div class="pie-menu-item" :class="{'choose':cutIndex3 == 2}" @click="changeItem3(2)">成交数量</div>
<!--          <div class="pie-menu-item" :class="{'choose':cutIndex3 == 3}" @click="changeItem3(3)">成交率</div>-->
        </div>
        <div id="pieChart2" class="charts-div" style="height:406px" ></div>
      </div>
      <div class="data-block order-table pie-table">
        <el-table :data="list3"  style="width: 100%;" class="data-table"  v-loading="listLoading3" show-summary :summary-method="getSummaries">
          <el-table-column
            align="center"
            label="询盘分类"
            min-width="150">
            <template slot-scope="scope">{{scope.row.type}}</template>
          </el-table-column>
          <el-table-column
            prop="inquiryCount"
            align="center"
            label="报价次数"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.inquiryCount}}
            </template>
          </el-table-column>
          <el-table-column
            prop="orderCount"
            align="center"
            label="成交次数"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.orderCount}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="成交率"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.orderRate}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="最长时间"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.maxTimes}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="最短时间"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.minTimes}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="平均时长"
            min-width="100">
            <template slot-scope="scope">
              {{scope.row.averageTimes}}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!--人员报价时长-->
    <div v-if="pUserInquiryPriceAnalysis">
      <div class="data-title" style="margin-top: 10px">
        <div class="title-left">
          <div class="title-item choose" >人员询盘报价时长分析</div>
        </div>
        <div class="title-right">
          <el-date-picker
            @change="getBarData2"
            style="width:210px;margin-right: 10px"
            size="mini"
            value-format="yyyy-MM-dd"
            v-model="listQuery4.date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
          <el-select @change="getBarData2" size="mini" placeholder="请选择品类" clearable style="margin-right: 10px;width:150px" v-model="listQuery4.goodsClass" >
            <el-option v-for="item in classList" :key="item.classId" :value="item.className" :label="item.className"></el-option>
          </el-select>
          <el-input size="mini" @change="getBarData2" v-if="listQuery4.goodsClass" placeholder="请输入厂家" clearable style="width:150px;margin-right: 10px"  v-model="listQuery4.brandName"></el-input>
          <el-select @change="getBarData2" size="mini" placeholder="请选择牌号" clearable style="margin-right: 10px;width:150px" v-model="listQuery4.kingGoodsId" filterable>
            <el-option
              v-for="item in goodsList"
              :key="item.kingId"
              :label="item.goodsSn"
              :value="item.kingId">
            </el-option>
          </el-select>
          <el-select size="mini" v-model="listQuery4.userIds"
                     collapse-tags
                     clearable @change="getBarData2"  placeholder="请选择人员" multiple>
            <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>

        </div>
      </div>
      <div class="data-block" style="margin-top: 10px">
        <div id="barChart2" style="height: 300px" class="charts-div"></div>
      </div>
    </div>


  </div>
</template>

<script>
import {pinquiryAnalysis,puserInquiryAnalysis,inquiryPriceAnalysis,userInquiryPriceAnalysis} from '@/api/data.js'
import echarts from "echarts";
import {formatDate} from '@/utils/date';
import store from '@/store';
import {mapGetters} from "vuex";
const defaultListQuery={
  "date" : [],
  "userIds" : [],
  "goodsClass" : "", //品类
  "brandName" : "",   //厂家
  kingGoodsId:''
};

const defaultListQuery2={
  "date" : [],
  "userIds" : [],
  "goodsClass" : "", //品类
  "brandName" : "",   //厂家
  kingGoodsId:''

};

const defaultListQuery3={
  "date" : [],
  "userIds" : [],
  "goodsClass" : "", //品类
  "brandName" : "",   //厂家
  kingGoodsId:''
};

const defaultListQuery4={
  "date" : [],
  "goodsClass" : "", //品类
  "brandName" : "",   //厂家
  kingGoodsId:'',
  "userIds" : [],
};



  export default {
    name: 'pumsinquiryData',
    data() {
      return {
        roles:store.getters.roles ? store.getters.roles : [],
        pickerOptions: {
          shortcuts: [{
            text: '今日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '本周',
            onClick(picker) {
              const now = new Date();
              // 获取今天是本周的第几天（0代表星期日，1代表星期一，...，6代表星期六）
              const dayOfWeek = now.getDay();
              // 计算本周第一天（星期一）的日期
              const startOfWeek = new Date(now);
              startOfWeek.setDate(now.getDate() - dayOfWeek + 1); // 调整为星期一
              // 计算本周最后一天（星期日）的日期
              const endOfWeek = new Date(startOfWeek);
              endOfWeek.setDate(startOfWeek.getDate() + 6); // 从星期一开始加6天得到星期日
              picker.$emit('pick', [startOfWeek, endOfWeek]);
            }
          }, {
            text: '本月',
            onClick(picker) {
              const now = new Date();
              // 获取当前月份和年份
              const month = now.getMonth();
              const year = now.getFullYear();
              // 计算本月第一天的日期
              const startOfMonth = new Date(year, month, 1);
              // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
              const startOfNextMonth = new Date(year, month + 1, 1);
              const endOfMonth = new Date(startOfNextMonth);
              endOfMonth.setDate(startOfNextMonth.getDate() - 1);
              picker.$emit('pick', [startOfMonth, endOfMonth]);
            }
          }, {
            text: '本年',
            onClick(picker) {
              const now = new Date();
              // 获取当前年份
              const year = now.getFullYear();
              // 计算本年第一天的日期（1月1日）
              const startOfYear = new Date(year, 0, 1);
              // 计算本年最后一天的日期（12月31日）
              const endOfYear = new Date(year, 11, 31);
              picker.$emit('pick', [startOfYear, endOfYear]);
            }
          }]
        },
        props:{multiple: true,label:'value',value:'label',emitPath:false},

        list1:[],
        listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
        listLoading1:false,
        pieChart:null,
        funnelChart:null,
        progressChart:null,
        inquiryCount: 0, //询盘次数
        priceCount: 0, //已报价次数
        cancelCount: 0, //已取消次数
        outTimeCount: 0, //已超时次数
        orderCount: 0, //已成交次数、已下单次数
        orderRate: 0, //询盘成交率
        waitPriceCount:0,//待报价
        waitOrderCount:0,  //待下单
        unDealCount:0,  //未成交

        barChart:null,
        listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
        listLoading2:false,

        listQuery3: JSON.parse(JSON.stringify(defaultListQuery3)),
        pieChart2:null,
        list3:[],
        listLoading3:false,
        cutIndex3:1,

        listQuery4: JSON.parse(JSON.stringify(defaultListQuery4)),
        barChart2:null,

        resizeObserver:null

      }
    },
    props: {
      userList: {
        type: Array,
        default: () => []
      },
      classList:{
        type: Array,
        default: () => []
      },
      goodsList:{
        type: Array,
        default: () => []
      }
    },
    filters: {



    },
    created(){
      this.listQuery1.date = this.getMonth()
      this.listQuery2.date = this.getMonth()
      this.listQuery3.date = this.getMonth()
      this.listQuery4.date = this.getMonth()
      this.$nextTick(()=>{
        this.getTopData()
        this.getBarData()
        this.getPieData2()
        this.getBarData2()
        // 智能响应式方案
        const elements = document.querySelectorAll('.charts-div');
        this.resizeObserver = new ResizeObserver(entries => {
          entries.forEach(entry => {
            if(entry.target.id == 'funnelChart'){
              this.funnelChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'pieChart'){
              this.pieChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'barChart'){
              this.barChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'pieChart2'){
              this.pieChart2.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }else if(entry.target.id == 'barChart2'){
              this.myChart.resize({
                animation: { duration: 300 }, // 启用平滑过渡
                throttle: 200 // 节流控制
              });
            }
          })
        });
        elements.forEach(el => {
          this.resizeObserver.observe(el);
        });
      })

    },

    beforeDestroy() {
      if (this.resizeObserver) {
        const elements = document.querySelectorAll('.charts-div');
        elements.forEach(el => {
          this.resizeObserver.unobserve(el);
        });
        this.resizeObserver.disconnect();
        this.funnelChart.dispose()
        this.pieChart.dispose();
        this.barChart.dispose()
        this.pieChart2.dispose();
        this.barChart2.dispose()
      }
    },
    components:{

    },
    computed:{
      pUserInquiryAnalysis() {
        if(this.roles.indexOf("pUserInquiryAnalysis") != -1){
          return true
        }else{
          return false
        }
      },
      pUserInquiryPriceAnalysis() {
        if(this.roles.indexOf("pUserInquiryPriceAnalysis") != -1){
          return true
        }else{
          return false
        }
      },

    },
    methods: {
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          const values = data.map(item => item[column.property]);
          if (index ==  1 || index == 2) {
            sums[index] = values.reduce((prev, curr) => {
              return prev + curr;
            }, 0);
            sums[index] += ' 次';
          } else {
            sums[index] = '--';
          }
        });

        return sums;
      },
      topage(type){
        let routeData
        switch (type) {
          case 'purchaseTimeReport' :
            routeData = this.$router.resolve({
              name: 'purchaseTimeReport',
              query: {dataDate: this.listQuery2.date}
            });
            break;
          case 'purchaseTimeReport2' :
            routeData = this.$router.resolve({
              name: 'purchaseTimeReport',
              query: {dataDate: this.listQuery4.date}
            });
            break;
        }
        window.open(routeData.href);
      },

      //获取本月时间
      getMonth(){
        const now = new Date();
        // 获取当前月份和年份
        const month = now.getMonth();
        const year = now.getFullYear();
        // 计算本月第一天的日期
        const startOfMonth = new Date(year, month, 1);
        // 计算下个月第一天的日期，然后减去一天得到本月的最后一天
        const startOfNextMonth = new Date(year, month + 1, 1);
        const endOfMonth = new Date(startOfNextMonth);
        endOfMonth.setDate(startOfNextMonth.getDate() - 1);
        return [formatDate(new Date(startOfMonth), 'yyyy-MM-dd'),formatDate(new Date(endOfMonth), 'yyyy-MM-dd')]
      },
      getTopData(){
        this.listQuery1.brandName = this.listQuery1.goodsClass ? this.listQuery1.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery1))
        listQuery.userIds = listQuery.userIds.join(",")
        pinquiryAnalysis(listQuery).then((res)=>{
            this.inquiryCount = res.inquiryCount
            this.priceCount = res.priceCount //已报价次数
            this.cancelCount = res.cancelCount//已取消次数
            this.outTimeCount = res.outTimeCount//已超时次数
            this.orderCount = res.orderCount //已成交次数、已下单次数
            this.orderRate = res.orderRate //询盘成交率
            this.waitPriceCount = res.waitPriceCount //待报价
            this.waitOrderCount = res.waitOrderCount  //待下单
            this.unDealCount = res.unDealCount  //未成交
            this.drawFunnel()
            this.drawPie()
        })
      },
      drawFunnel(){
        this.funnelChart = echarts.init(document.getElementById('funnelChart'),null,{renderer: 'canvas',useDirtyRect: false});
        let option = {
          toolbox: {
            show:true,
            feature: {
              myTool1: {
                show: true,
                title: '全屏',
                icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
                onclick: () => {
                  const chartDom = document.getElementById('funnelChart');
                  if (chartDom.requestFullscreen) chartDom.requestFullscreen();
                  if (document.exitFullscreen) document.exitFullscreen();
                }
              }
            }
          },
          series: [
            {
              name: 'Funnel',
              type: 'funnel',
              left: '10%',
              top: 20,
              bottom: 20,
              width: '40%',
              sort: 'descending',
              gap: 2,
              label: {
                show: true,
                position: 'outside',
                formatter: function(params) {
                  var name = params.name;
                  var maxLabelLength = 12; // 可根据需要调整
                  // 如果标签文本长度超过最大显示长度，则截断并添加省略号
                  if (name.length > maxLabelLength) {
                    name = name.substring(0, maxLabelLength) + '\n'+name.substring(maxLabelLength, name.length);
                  }
                  return `{num|${params.value}}\n{name|${name}}`
                }, // 显示数据项名称、值
                rich: {
                  num: {
                    fontSize: 20,
                    fontWeight:'bold',
                    color: '#5b5b5b'
                  },
                  name: {
                    fontSize: 16,
                    color: '#999'
                  },
                },
              },

              labelLine: {
                length: 40,
                lineStyle: {
                  width: 1,
                  type: 'solid'
                }
              },
              itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
              },
              emphasis: {
                label: {
                  fontSize: 14
                }
              },
              data: [
                { value: this.inquiryCount, name: '询盘数量(不含一口价)',itemStyle:{color:'#4e75ec'} },
                { value: this.priceCount, name: '报价数量' ,itemStyle:{color:'#ffbb70'}},
                { value: this.orderCount, name: '成交数量',itemStyle:{color:'#91cc75'} },

              ]
            }
          ]
        };
        this.funnelChart.setOption(option);
      },
      drawPie(){
        let res = [{type:'待报价',value:this.waitPriceCount},
          {type:'待下单',value:this.waitOrderCount},
          {type:'未成交',value:this.unDealCount},
          {type:'已下单',value:this.orderCount},
          {type:'已取消',value:this.cancelCount},
          {type:'已超时',value:this.outTimeCount},]
        this.pieChart = echarts.init(document.getElementById('pieChart'),null,{renderer: 'canvas',useDirtyRect: false});
        let data = []
        let colorList = ['#4e75ec','#ffbb70','#91cc75','#ee6666','#73c0de','#3ba272','#fc8452','#9a60b4','#ea7ccc','#b8c85f']
        let name = 'type'
        let value = 'value'
        res.forEach((el,index)=>{
          if(el[value] > 0){
            data.push({
              name:el[name],
              value:el[value],
              itemStyle:{color:colorList[index]}
            })
          }
        })
        let roseType =  ''
        let radius =  ['50%', '70%']
        let option = {
          toolbox: {
            show:true,
            feature: {
              myTool1: {
                show: true,
                title: '全屏',
                icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
                onclick: () => {
                  const chartDom = document.getElementById('pieChart');
                  if (chartDom.requestFullscreen) chartDom.requestFullscreen();
                  if (document.exitFullscreen) document.exitFullscreen();
                }
              }
            }
          },
          series: [
            {
              type: 'pie',
              label: {
                normal: {
                  show: true,
                  alignTo: 'edge',
                  minMargin: 5,
                  edgeDistance: 10,
                  lineHeight: 20,
                  align: 'right', // 标签文本对齐方式
                  formatter: function(params) {
                    var name = params.name;
                    var maxLabelLength = 6; // 可根据需要调整
                    // 如果标签文本长度超过最大显示长度，则截断并添加省略号
                    if (name.length > maxLabelLength) {
                      name = name.substring(0, maxLabelLength) + '\n'+name.substring(maxLabelLength, name.length);
                    }
                    return `{num|${params.value}}\n{name|${name}}`
                  }, // 显示数据项名称、值
                  rich: {
                    num: {
                      fontSize: 20,
                      fontWeight:'bold',
                      color: '#5b5b5b'
                    },
                    name: {
                      fontSize: 16,
                      color: '#999'
                    },
                  }
                }
              },
              radius: radius,
              center: ['50%', '50%'],
              roseType: roseType,
              labelLine: {
                normal: {
                  show: true,
                  length: 10,
                  length2: 15,
                  maxSurfaceAngle: 80
                }
              },
              itemStyle: {
                // 这里的颜色会应用到所有的扇区上，如果想要为每个扇区指定不同的颜色，需要使用 data 中的 itemStyle
                borderRadius: 10, // 统一设置圆角半径（但这种方式可能不被所有版本支持，具体看ECharts文档）
                borderColor: '#fff', // 设置扇区边框颜色
                borderWidth: 1 // 设置扇区边框宽度
              },
              data: data
            }
          ]
        };
        this.pieChart.setOption(option);
      },


      getBarData(){
        this.listQuery2.brandName = this.listQuery2.goodsClass ? this.listQuery2.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery2));
        listQuery.userIds = listQuery.userIds.join(',')
        this.listLoading2 = true;
        puserInquiryAnalysis(listQuery).then((res)=>{
          this.listLoading2 = false
          this.drawBar(res)
        })

      },
      drawBar(res){
        this.barChart = echarts.init(document.getElementById('barChart'),null,{renderer: 'canvas',useDirtyRect: false});
        // 假设我们有目标销量和实际销量的数据
        let salesData = res

        // 准备数据
        let categories = salesData.map(item => item['userRealName']);  //x轴
        let y = salesData.map(item => item['inquiryCount']);//询盘数量
        let y1 = salesData.map(item => item['priceCount']);//报价数量
        let y2 = salesData.map(item => item['orderCount']);//成交数量
        let y3 = salesData.map(item => item['orderRate']); //成交率


        const minShowItems = 15; // 触发滚动的最小数据量
        let option = {
          tooltip: {
            trigger: 'axis',
            backgroundColor:'none',
            formatter: function(params) {
              let html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  <div style="color:#8b8b8b;font-size: 14px;">询盘数量：<span style="color:#6084f2;font-weight: bold">${params[0].value}次</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">报价数量：<span style="color:#ffc27b;font-weight: bold">${params[1].value}次</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">成交数量：<span style="color:#6ad1ad;font-weight: bold">${params[2].value}次</span></div>
                  <div style="color:#8b8b8b;font-size: 14px;">成交率：<span style="color:#ef915d;font-weight: bold">${params[3].value}%</span></div>
                  </div>`;
              return html;
            }
          },
          legend: {
            data: ['询盘数量', '报价数量','成交数量','成交率'],
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
            orient: 'horizontal',
            x: '50%',        // 水平起点为容器宽度的15%
            y: 20,           // 垂直起点50px
          },
          grid: {
            left: 50,          // 左侧留空比例
            right: 30,          // 右侧留空
            bottom:30,
            top:80,
            containLabel: true,   // 确保标签不被截断
          },
          dataZoom: [
            {
              type: 'slider',      // 滑动条型dataZoom（必须声明）
              height: 10,           // 滚动条高度
              bottom:16,
              show: salesData.length > minShowItems,          // 默认显示
              xAxisIndex: 0,       // 控制第一个xAxis
              zoomLock: true,        // 禁止缩放（仅滚动）
              start: 0,
              end: Math.min(100, (minShowItems / salesData.length) * 100), // 动态计算初始窗口
            }
          ],
          xAxis: {
            type: 'category',
            data: categories,
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 14,        // 字体大小
            },
            axisTick: {
              show: false,          // 显示刻度线
            },
          },
          yAxis: [
            {
              type: 'value',
              name: '次数',
              nameTextStyle:{
                color:'#898989'
              },
              position: 'left',
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 10,        // 字体大小
              },
              splitLine: {
                show: true,                    // 需手动开启
                lineStyle: {
                  color: '#ebebeb',  // 半透明细线
                  width: 0.5
                }
              }
            },
            {
              type: 'value',
              name: '成交率',
              nameTextStyle:{
                color:'#898989'
              },
              position: 'right',
              axisLine: {
                lineStyle: {
                  color: '#dadada', // X轴轴线颜色
                }
              },
              axisLabel: {
                color: '#818181',       // 字体颜色
                fontSize: 10,        // 字体大小
              },
              splitLine: {
                show: false,                    // 需手动开启
              }
            },
          ],
          series: [
            {
              name:'询盘数量',
              type: 'bar',
              data: y,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#6084f2' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
            },
            {
              name: '报价数量',
              type: 'bar',
              data: y1,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#ffc27b' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
            },
            {
              name: '成交数量',
              type: 'bar',
              data: y2,
              yAxisIndex: 0,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                  { offset: 0, color: '#6cd2ae' },
                  { offset: 1, color: '#ffffff' }
                ])
              },
              barWidth:16,
            },
            {
              name: '成交率',
              type: 'line',
              data: y3,
              yAxisIndex: 1,
              lineStyle: {
                color: '#ee905c',
                width: 2,
              },
              symbol: 'emptyCircle',       // 顶点形状（circle/diamond/triangle等）
              symbolSize: 8,         // 顶点大小
              itemStyle: {
                color: '#ee905c',     // 顶点填充色
                borderColor: '#ee905c',  // 顶点边框色
                borderWidth: 1        // 边框粗细
              }
            },

          ]
        };
        this.barChart.setOption(option);
        this.barChart.on('click', (params)=> {
          this.topage('purchaseTimeReport')
        })
      },

      changeItem3(index){
        this.cutIndex3 = index
        this.pieChart2.clear()
        this.$nextTick(()=>{
          this.drawPie2()
        })
      },
      getPieData2(){
        this.listQuery3.brandName = this.listQuery3.goodsClass ? this.listQuery3.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery3))
        listQuery.userIds = listQuery.userIds.join(",")
        this.listLoading3 = true
        inquiryPriceAnalysis(listQuery).then((res)=>{
          this.list3 = res
          this.listLoading3 = false
          this.drawPie2()
        })
      },
      drawPie2(){
        let res = []
        let value = ''
        if(this.cutIndex3 == 1 ){
          value = 'inquiryCount'
        }else if(this.cutIndex3 == 2){
          value = 'orderCount'
        }else if(this.cutIndex3 == 3){
          value = 'orderRate'
        }
        this.list3.forEach((el)=>{
          res.push({name:el.type,value:el[value]})
        })
        this.pieChart2 = echarts.init(document.getElementById('pieChart2'),null,{renderer: 'canvas',useDirtyRect: false});
        let data = []
        let colorList = ['#4e75ec','#ffbb70','#91cc75','#ee6666','#73c0de','#3ba272','#fc8452','#9a60b4','#ea7ccc','#b8c85f']
        res.forEach((el,index)=>{
          if(el['value'] > 0){
            data.push({
              name:el['name'],
              value:el['value'],
              itemStyle:{color:colorList[index]}
            })
          }
        })
        console.log("data",data)
        let roseType =  ''
        let radius =  ['50%', '70%']
        let option = {
          series: [
            {
              type: 'pie',
              label: {
                normal: {
                  show: true,
                  alignTo: 'edge',
                  minMargin: 5,
                  edgeDistance: 10,
                  lineHeight: 15,
                  align: 'right', // 标签文本对齐方式
                  formatter: function(params) {
                    var name = params.name;
                    var maxLabelLength = 6; // 可根据需要调整
                    // 如果标签文本长度超过最大显示长度，则截断并添加省略号
                    if (name.length > maxLabelLength) {
                      name = name.substring(0, maxLabelLength) + '\n'+name.substring(maxLabelLength, name.length);
                    }
                    return `{num|${params.value}}\n{name|${name}}`
                  }, // 显示数据项名称、值
                  rich: {
                    num: {
                      fontSize: 20,
                      fontWeight:'bold',
                      color: '#5b5b5b'
                    },
                    name: {
                      fontSize: 14,
                      color: '#999'
                    },
                  }
                }
              },
              radius: radius,
              center: ['50%', '50%'],
              roseType: roseType,
              labelLine: {
                normal: {
                  show: true,
                  length: 10,
                  length2: 15,
                  maxSurfaceAngle: 80
                }
              },
              itemStyle: {
                // 这里的颜色会应用到所有的扇区上，如果想要为每个扇区指定不同的颜色，需要使用 data 中的 itemStyle
                borderRadius: 10, // 统一设置圆角半径（但这种方式可能不被所有版本支持，具体看ECharts文档）
                borderColor: '#fff', // 设置扇区边框颜色
                borderWidth: 1 // 设置扇区边框宽度
              },
              data: data
            }
          ]
        };
        this.pieChart2.setOption(option);
      },

      getBarData2(){
        this.listQuery4.brandName = this.listQuery4.goodsClass ? this.listQuery4.brandName : ''
        let listQuery = JSON.parse(JSON.stringify(this.listQuery4));
        listQuery.userIds = listQuery.userIds.join(',')
        userInquiryPriceAnalysis(listQuery).then((res)=>{
          this.drawBar2(res)
        })

      },
      drawBar2(oldData){
        this.barChart2 = echarts.init(document.getElementById('barChart2'),null,{renderer: 'canvas',useDirtyRect: false});
        let unit = '次'
        let self  = this
        let categories = oldData.data.map(item => item.userRealName)
        let colorList = ['#4e75ec','#ffbb70','#91cc75','#ee6666','#73c0de','#3ba272','#fc8452','#9a60b4','#ea7ccc','#b8c85f']
        let series = []
        let legend = oldData.series.map(item => item.label)

        let dataList = {}
        oldData.series.forEach((el,index)=>{
          dataList[el.key] = []
          oldData.data.forEach((ee)=>{
            dataList[el.key].push(Number(ee[el.key]))
          })
          if(el.key != 'orderRate'){
            series.push({
              name:el.label,
              data:dataList[el.key],
              barWidth:16,
              barGap: '10%', // 不同系列间的柱子间隔
              barCategoryGap: '10%', // 同一系列内柱子间隔
              type: 'bar',
              stack: 'total',
              yAxisIndex: 0,
              itemStyle: {
                color: colorList[index]
              },
            })
          }else{
            series.push({
              name:el.label,
              data:dataList[el.key],
              type: 'line',
              yAxisIndex: 1,
              itemStyle: {
                color: colorList[index],
                borderColor: colorList[index],  // 顶点边框色
                borderWidth: 1        // 边框粗细
              },
              lineStyle: {
                color: colorList[index],
                width: 2,
              },
              symbol: 'emptyCircle',       // 顶点形状（circle/diamond/triangle等）
              symbolSize: 8,         // 顶点大小
            })
          }
        })
        const minShowItems = 15; // 触发滚动的最小数据量
        let option = {

          tooltip: {
            trigger: 'axis',
            backgroundColor:'none',
            formatter: function(params) {
              let con = ''
              for(let i=0;i<params.length;i++){
                let condiv = `<div style="color:#8b8b8b;font-size: 14px;">${params[i].seriesName}：<span style="color:${colorList[i]};font-weight: bold">${params[i].value}</span>${params[i].seriesName.indexOf('率') != -1 ? '%' : unit}</div>`
                con = con+condiv
              }
              let html = ''
              html = `<div style="padding:12px 30px 12px 12px;line-height: 26px;background:rgba(255,255,255,0.8);box-shadow: 2px 2px 5px rgba(0,0,0,0.3);border-radius: 8px;border:1px solid #5e83f1">
                  <div style="color:#000;font-size: 16px;font-weight: bold;">${params[0].name}</div>
                  ${con}
                  </div>`;
              return html;
            }
          },
          legend: {
            data: legend,
            textStyle: {
              fontSize: 14 // 设置字体大小为16
            },
            y: 40,           // 垂直起点50px
          },
          grid: {
            left: 50,          // 左侧留空比例
            right: 30,          // 右侧留空
            bottom:30,
            top:80,
            containLabel: true,   // 确保标签不被截断
          },
          dataZoom: [
            {
              type: 'slider',      // 滑动条型dataZoom（必须声明）
              height: 10,           // 滚动条高度
              bottom:16,
              show: oldData.data.length > minShowItems,          // 默认显示
              xAxisIndex: 0,       // 控制第一个xAxis
              zoomLock: true,        // 禁止缩放（仅滚动）
              start: 0,
              end: Math.min(100, (minShowItems / oldData.data.length) * 100), // 动态计算初始窗口
            }
          ],
          xAxis: {
            type: 'category',
            data: categories,
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 14,        // 字体大小
            },
            axisTick: {
              show: false,          // 显示刻度线
            },
          },
          yAxis: [{
            type: 'value',
            nameTextStyle:{
              color:'#898989'
            },
            position: 'left',
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 10,        // 字体大小
            },
            splitLine: {
              show: true,                    // 需手动开启
              lineStyle: {
                color: '#ebebeb',  // 半透明细线
                width: 0.5
              }
            }
          },{
            type: 'value',
            name: '成交率',
            nameTextStyle:{
              color:'#898989'
            },
            position: 'right',
            axisLine: {
              lineStyle: {
                color: '#dadada', // X轴轴线颜色
              }
            },
            axisLabel: {
              color: '#818181',       // 字体颜色
              fontSize: 10,        // 字体大小
            },
            splitLine: {
              show: false,                    // 需手动开启
            }
          },
          ],
          series: series
        };

        this.barChart2.setOption(option);
        this.barChart2.on('click', (params)=> {
          this.topage('purchaseTimeReport2')
        })
      },

    }
  }
</script>


